package com.spi.sentinel;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

@Component
@Aspect
@Slf4j
public class RateLimiterAspect {

    @Autowired
    private TokenBucketLimiter tokenBucketLimiter ;

    @Around("@annotation(com.spi.sentinel.RateLimiter)")
    public Object reteLimit(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            RateLimiter annotation = method.getAnnotation(RateLimiter.class);
            String key = annotation.key();
            double v = annotation.permitsPerSecond();
            String message = annotation.message();
            long timeout = annotation.timeout();
            TimeUnit timeUnit = annotation.timeUnit();
            System.out.println("参数打印===============");
            log.info("{}:{}","key==",key);
            log.info("{}:{}","permitsPerSecond==",v);
            log.info("{}:{}","message==",message);
            log.info("{}:{}","timeout==",timeout);
            log.info("{}:{}","timeUnit==",timeUnit);
            boolean b = tokenBucketLimiter.tryAcquire(
                    key,
                    v,
                    message,
                    timeout,
                    timeUnit
            );
            if (!b){
                System.out.println("服务器繁忙 限流器开始工作 请稍后重试===");
                throw new RuntimeException() ;
            }
            return joinPoint.proceed() ;
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("aop切面报错===" + e.getMessage());
            throw new RuntimeException(e.getMessage()) ;
        }

    }



















}
